package com.jacobson.huobi

import android.content.Context
import androidx.multidex.MultiDex
import com.jacobson.core.base.BaseApplication
import com.jacobson.core.widget.logger.LoggerFactory
import com.jacobson.core.widget.storage.GlobalStorage
import com.jacobson.huobi.common.expansion.currentTimeSecond
import com.jacobson.huobi.entities.SymbolInfo
import com.jacobson.huobi.entities.SystemActiveInfo
import com.jacobson.huobi.mvp.OnePXActivity
import com.jacobson.huobi.mvp.others.ScreenListener
import com.jacobson.huobi.services.DaemonService
import com.jacobson.huobi.services.DaemonServiceReceiver
import com.jacobson.huobi.services.WebsocketService
import com.jacobson.huobi.services.WebsocketServiceReceiver
import com.jacobson.huobi.utils.KeepLiveManager
import com.jacobson.huobi.utils.NotificationHelper
import com.jacobson.huobi.utils.SettingProperties
import com.jacobson.huobi.utils.SoundUtil
import com.marswin89.marsdaemon.DaemonClient
import com.marswin89.marsdaemon.DaemonConfigurations
import com.marswin89.marsdaemon.DaemonConfigurations.DaemonListener
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.bugly.crashreport.CrashReport.UserStrategy
import java.io.BufferedReader
import java.io.FileReader
import java.util.*
import kotlin.collections.ArrayList


class HuobiApplication : BaseApplication(), ScreenListener.ScreenStateListener {
    private lateinit var daemonClient: DaemonClient
    private val logger = LoggerFactory.getLogger()
    private lateinit var screenListener: ScreenListener

    companion object {
        private const val PROCESS_NAME_WEBSOCKET = "com.jacobson.huobi:remote"
        private const val PROCESS_NAME_DAEMON = "com.jacobson.huobi:remote_daemon"
        fun getInstance(): HuobiApplication {
            return instance
        }

        private lateinit var instance: HuobiApplication
        var onePxActivity: OnePXActivity? = null
    }

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        MultiDex.install(this)
        // 启动守护进程
        daemonClient = DaemonClient(createDaemonConfigurations())
        daemonClient.onAttachBaseContext(base)
        // 创建交易对同步数组列表
        GlobalStorage.put(
            Constants.KEY_SYMBOL_LIST,
            Collections.synchronizedList(ArrayList<SymbolInfo>())
        )
    }

    private fun initBugly() {
        // 获取当前进程名
        val processName = getProcessName(android.os.Process.myPid())
        // 设置是否为上报进程
        val strategy = UserStrategy(applicationContext)
        strategy.isUploadProcess = processName == null || processName == packageName
        // 初始化Bugly
        CrashReport.initCrashReport(this, Constants.APP_ID_FOR_BUGLY, false, strategy)
    }

    /** 守护进程配置 */
    private fun createDaemonConfigurations(): DaemonConfigurations {
        return DaemonConfigurations(DaemonConfigurations.DaemonConfiguration(
            PROCESS_NAME_WEBSOCKET,
            WebsocketService::class.java.canonicalName,
            WebsocketServiceReceiver::class.java.canonicalName
        ), DaemonConfigurations.DaemonConfiguration(
            PROCESS_NAME_DAEMON,
            DaemonService::class.java.canonicalName,
            DaemonServiceReceiver::class.java.canonicalName
        ), object : DaemonListener {
            override fun onPersistentStart(context: Context?) {
                logger.d("onPersistentStart")
            }

            override fun onDaemonAssistantStart(context: Context?) {
                logger.d("onDaemonAssistantStart")
            }

            override fun onWatchDaemonDaed() {
                logger.d("onWatchDaemonDead")
            }
        })
    }

    override fun onCreate() {
        instance = this
        super.onCreate()

        // 连接状态
        initSymbolActiveInfo()
        // 初始化设置的配置类
        SettingProperties.init(this)
        // 初始化声音帮助类
        SoundUtil.getInstance().init(this)
        // 初始化通知栏配置类
        NotificationHelper.init(this)
        // 监听锁屏状态
        screenListener = ScreenListener(this)
        screenListener.begin(this)
        // Bugly
        initBugly()
    }

    /** 系统连接状态初始化默认 */
    private fun initSymbolActiveInfo() {
        val arr = ArrayList<SystemActiveInfo>(6)
        arr.add(SystemActiveInfo(1, 1, "#654525", currentTimeSecond()))
        arr.add(SystemActiveInfo(2, 1, "#654525", currentTimeSecond()))
        arr.add(SystemActiveInfo(3, 1, "#a2d522", currentTimeSecond()))
        arr.add(SystemActiveInfo(4, 1, "#ff545a", currentTimeSecond()))
        arr.add(SystemActiveInfo(5, 1, "#ff545a", currentTimeSecond()))
        arr.add(SystemActiveInfo(6, 1, "#ff545a", currentTimeSecond()))
        GlobalStorage.put(Constants.KEY_SYSTEM_STATUS, arr)
    }

    override fun onScreenOn() {
//        logger.d("开屏状态 >>> 启动前台保活服务")
        // 开屏后打开后台保活服务
//        KeepLiveManager.startForegroundService()
    }

    override fun onScreenOff() {
//        logger.d("锁屏状态 >>> 启动一像素视图保活")
        // 锁屏状态，启动一像素视图保活
        KeepLiveManager.startOnePxActivity(this)
    }

    override fun onUserPresent() {
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private fun getProcessName(pid: Int): String? {
        BufferedReader(FileReader("/proc/$pid/cmdline")).use { reader ->
            return reader.readLine()?.takeIf { it.isNotEmpty() }?.trim { it <= ' ' }
        }
    }
}